<template>
	<view class="pr">
		<u-navbar :title="title" titleBold titleColor="#333">
			<view class="flex1 row-right flex fs30 color-333 pr20" v-if="$params.group_id"
				@click="$jump('/pages/message/group_info',$params)">
				<u-icon name="more-circle" size="44" />
			</view>
		</u-navbar>
		<block v-if="data.consult&&data.consult.status==2">
			<view class="h80 bg-f5f pl28 flex pr28 pf w-max fs24 z-index1">
				<view class="flex1">
					<u-count-down :timestamp="data.consult&&data.consult.countdown||0" color="#999" bgColor="#0000"
						fontSize="24" separatorSize="24" />
					<text class="color-999 ">后结束咨询</text>
				</view>
				<view class="color-red" @click="finishConsult">结束咨询</view>
			</view>
			<view class="h80"></view>
		</block>
		<view class="flex row-center h80" v-if="isLoad">
			<u-loading mode="circle"></u-loading>
		</view>
		<view class="flex row-center pt10" v-if="allLoad">
			<view class="color-999 fs22">到顶了~</view>
		</view>

		<view class="p20" :id="'msg'+item.id" :class="item.identify=='my'?'my_chat':'you_chat'"
			v-for="(item,index) in list" :key="index">

			<view class="flex row-center pb20" v-if="item.create_time">
				<view class="tc fs20 color-fff pl10 pr10 lh2 radius4" style="background: #0003;">
					{{item.create_time}}
				</view>
			</view>
			<view class="tc fs24" v-if="item.is_recall">
				<text class="" v-if="item.identify=='my'">你</text>
				<text v-else>"{{item.from_info.name}}"</text>
				<text>撤回了一条消息</text>
			</view>
			<view class="flex chat_line" v-else>
				<view class="als-s">
					<u-avatar v-if="item.from_info" :src="item.from_info.avatar" size="80" mode=""
						@click="$jump('/pages/message/friend_info',{to_identify:item.from_info.identify,to_id:item.from_info.id})">
					</u-avatar>
				</view>
				<view class="w20"></view>
				<view class="flex">
					<view class="p20 radius8 text_bg" @longpress="msg_longpress(item)" @touchend.prevent
						hover-stop-propagation>
						<text v-if="item.message&&item.message.type=='text'">{{item.message.content}}</text>
					</view>
				</view>
				<view class="w10"></view>
				<block v-if="item.identify=='my'">
					<view class="color-999 fs24 " v-if="item.isread==0">未读</view>
					<view class="color-999 fs24 " v-else>已读</view>
				</block>
			</view>
		</view>

		<view class="h100" id="bottom"></view>
		<view class="" :style="[{height:keyHeight+'px'}]"></view>
		<view class="fixed bottom0 left0 p20 w-max bg-f5f border-t ">
			<view class="flex col-bottom">
				<view class="w-max flex row-center col-center color-666" v-if="data.is_remove==1">
					<u-icon name='error-circle' />
					<text class="ml10">无法在已退出的群聊中发送消息</text>
				</view>
				<block v-else>
					<view class="bg-fff w-max p10 radius8 fs32 color-999"
						v-if="data.consult&&data.consult.status!=2&&data.consult.status!=1">咨询已结束</view>
					<block v-else>
						<textarea fixed placeholder="说点什么~" v-model="message" @confirm="sed_text(message)"
							confirm-type="send" auto-height :adjust-position="false" confirm-hold
							class="bg-fff w-max p10 radius8 fs32 " style="line-height: 1.2em;" cursor-spacing="50" />
					</block>
					<view class="w20"></view>
					<view class="pb6">
						<u-button type="success" :disabled="!message" ripple size="mini"
							@touchend.prevent="sed_text(message)"> 发送
						</u-button>
					</view>
				</block>
			</view>
			<view class="" :style="[{height:keyHeight+'px'}]"></view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				message: '',
				data: {
					consult: ''
				},
				list: [],
				isLoad: false, //加载中
				allLoad: false, //
				keyHeight: 0,
				scrollTop: 0
			};
		},
		computed: {
			title() {
				let data = this.data || ''
				let title = data.remarks || data.name || ''
				if (this.$params.group_id) title = title + (data.num ? '(' + (data.num || '') + ')' : '')
				return title || '聊天界面'
			}
		},
		onLoad() {
			uni.$on('chat:chat', this.onChat)
			this.loadHistory(0)
			// #ifdef APP-PLUS
			uni.onKeyboardHeightChange(this.onKey)
			// #endif
		},
		onShow() {
			this.chatInfo()
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop
			if (e.scrollTop == 0) this.loadHistory('top')
		},
		onUnload() {
			// #ifdef APP-PLUS
			uni.offKeyboardHeightChange(this.onKey) // 需传入与监听时同一个的函数对象
			// #endif
		},
		methods: {
			readChat(item) { //清除已读
				this.$request('/platform/message/readChat', {
					room: this.data.room
				})
			},
			msg_longpress(item) {
				let arr = []

				let is_recall = false
				if (item.identify == 'my' || this.data.is_leader == 1) {
					is_recall = (item.timestamp * 1 + (this.$config.recall_time || 60) * 1) >= new Date().getTime() / 1000
				}
				if (is_recall) {
					arr.push({
						name: '撤回',
						fn: () => this.recallChat(item)
					})
				}
				if (item.message.type == 'text') {
					arr.push({
						name: '复制',
						fn: () => this.$tool.copy(item.message.content)
					})
				}
				this.$tool.showActionSheet(arr)
			},
			// record_id：聊天记录id
			async recallChat(item) {
				let res = await this.$request('/platform/message/recallChat', {
					record_id: item.id
				})
				item.is_recall = 1
			},

			onKey(res) { //监听键盘弹起
				this.keyHeight = res.height
				if (!res.height) return
				this.$nextTick(() => {
					uni.pageScrollTo({
						scrollTop: this.scrollTop + res.height,
						duration: 0
					})
				})
			},
			chatInfo() { //获取聊天对象
				let api = '/platform/message/userInfo'
				if (this.$params.group_id) api = '/platform/message/groupInfo'
				if (this.$params.consult_id) api = '/platform/consult/consultInfo'
				this.$request(api, this.$params).then(res => {
					this.data = res.data || ''
				})
			},
			loadHistory(e) { //消息记录
				if (this.allLoad) return //内容全部加载
				if (this.isLoad) return //加载中 防止重复请求
				this.isLoad = true
				let params = {
					...this.$params,
					page: this.page++
				}
				let view_id = this.list[0]?.id || ''
				let api = '/platform/message/chatRecord'
				if (this.$params.group_id) api = '/platform/message/groupChatRecord'
				if (this.$params.consult_id) api = '/platform/consult/chatRecord'
				this.$request(api, params).then(res => {
					let list = res.data.data || []
					this.isLoad = false
					if (!list.length) return this.allLoad = true
					this.list.unshift(...list)
					this.$nextTick(() => {
						if (e === 0) {
							uni.pageScrollTo({
								selector: '#bottom',
								duration: 0,
							})
						} else {
							if (view_id) {
								uni.pageScrollTo({
									selector: '#msg' + view_id,
									duration: 0,
									complete: () => {}
								})
							}
						}
					});
				}).catch(err => {
					this.isLoad = false
				})
			},
			sed_text(content) { //发送文字
				if (!content) return this.$msg('不能发送空白')
				let message = {
					type: 'text',
					content
				}
				this.send_api(message)
				this.message = ''
			},
			send_api(message) { //发送消息
				let params = {
					...this.$params,
					message
				}
				let api = '/platform/message/sendChat'
				if (this.$params.group_id) api = '/platform/message/sendGroupChat'
				if (this.$params.consult_id) api = '/platform/consult/sendChat'
				this.$request(api, params).then(res => {
					let data = res.data
					data.id = data.id || (this.list[this.list.length - 1].id * 1 + 1)
					// this.list.push(data)
					// this.$nextTick(()=>{
					// 	uni.pageScrollTo({
					// 		selector: '#msg' + data.id,
					// 		duration: 200,
					// 	})
					// })
					this.push_msg(data)
				})
			},
			push_msg(data) {
				this.list.push(data)
				this.$nextTick(() => {
					uni.pageScrollTo({
						selector: '#msg' + data.id,
						duration: 200,
					})
				})
			},
			onChat(data) {
				console.log(data);
				if (data.room != this.data.room) return
				if (data) {} else {}
				this.push_msg(data)
				this.$u.throttle(this.readChat, 500)
			},
			timeFrom(time) {
				return this.$u.timeFrom(time, 'yyyy年mm月dd日 hh:MM:ss')
			},
			finishConsult() {
				this.$showModal('结束咨询').then(res => {
					this.$request('platform/consult/finishConsult', this.$params).then(res => {
						this.$msg(res.msg)
						this.$navBack(1, 1000)
					})
				})
			},
			scrollBottom() { // 滚动到底
				uni.pageScrollTo({
					selector: '#bottom',
					duration: 0,
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		// height: 100%;
	}

	:deep(.uni-textarea-compute) {
		max-height: calc(7em * 1.2);
	}

	.flex-right {}

	.my_chat {
		.chat_line {
			flex-direction: row-reverse !important;
		}

		.text_bg {
			background: #95ec69;
		}
	}

	.you_chat {


		.text_bg {
			background: #fff;
		}
	}
</style>